<?php
///
namespace lxsphp\Core;

///
use lxsphp\App;

/**
 * 核心 - [调试]类
 *
 * @version $Id: Debugger.php 195 2014-07-18 09:35:22Z linsir123 $
 * @package lxsphp\Core
 */
class Debugger
{
	/**
	 * 配置
	 *
	 * @var array
	 */
	public $conf = array();

	/**
	 * 状态
	 *
	 * @var bool
	 */
	private $_flag = false;

	/**
	 * 计数器
	 *
	 * @var int
	 */
	private $_count;

	/**
	 * 开始时间
	 *
	 * @var int
	 */
	private $_timeStart;

	/**
	 * 日志队列
	 *
	 * @var array
	 */
	private $_logList;

	/**
	 * 日志保存文件
	 *
	 * @var string
	 */
	private $_logFile;

	/**
	 * 构造函数
	 */
	public function __construct()
	{
		///
		$this->conf = App::o("app.debugger");

		///
		$this->_flag = ! empty($this->conf['handler']);
		if ($this->conf['handler'] == 3) {
			$max = intval($this->conf['rand']);
			if ($max > 1)
				$this->_flag = mt_rand(1, $max) == 1;
		}

		///
		if ($this->_flag) {
			switch ($this->conf['handler']) {
				case 2:
					App::$I->getHook()->addHook('end', array($this, 'displayLog'));
					break;
				case 3:
					$dir = CACHE_DIR . 'runtime/pid/';
					$this->_logFile = sprintf("%s/%s.txt", $dir, uniqid());
					App::$I->getLog()->mkdir($dir);
					break;
			}
		}
	}

	/**
	 * 输出调试
	 */
	public function displayLog()
	{
		///
		if (! $this->_flag)
			return;

		///
		echo "<pre>";
		echo "##########################[Debuger]##########################\r\n";
		echo "The following is the debug information:\r\n";
		foreach ($this->_logList as $i => $log) {
			$log = str_replace(array("\r\n", "\r", "\n"), " ", $log);
			echo $i . " => " . $log . "\r\n";
		}
		echo "##########################[\\Debuger]##########################\r\n";
		echo "</pre>";
	}

	/**
	 * 记录调试内容
	 *
	 * @param string $message
	 */
	public function log($message)
	{
		///
		if (! $this->_flag)
			return;

		///
		$log = sprintf("%d: [%s s] %s\r\n",
			++$this->_count,
			$this->_timerStop(),
			$message);

		///
		switch ($this->conf['handler']) {
			case 1:
				echo nl2br($log);
				break;
			case 2:
				$this->_logList[] = $log;
				break;
			case 3:
				@file_put_contents($this->_logFile, $log, FILE_APPEND);
				break;
		}
	}

	/**
	 * 开启计时器
	 */
	public function timerStart()
	{
		///
		if (! $this->_flag)
			return;

		///
		$this->_timeStart = $this->_getMtime();
	}

	/**
	 * 返回执行时间
	 *
	 * @return float
	 */
	private function _timerStop()
	{
		///
		$tmp = $this->_getMtime() - $this->_timeStart;

		///
		return number_format($tmp, 6);
	}

	/**
	 * 返回`microtime`
	 *
	 * @return float
	 */
	private function _getMtime()
	{
		///
		list($usec, $sec) = explode(" ", microtime());

		///
		return ((float)$usec + (float)$sec);
	}
}
